// The contents of this file are subject to the Mozilla Public License Version
// 1.1
//(the "License"); you may not use this file except in compliance with the
//License. You may obtain a copy of the License at http://www.mozilla.org/MPL/
//
//Software distributed under the License is distributed on an "AS IS" basis,
//WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
//for the specific language governing rights and
//limitations under the License.
//
//The Original Code is "The Columba Project"
//
//The Initial Developers of the Original Code are Frederik Dietz and Timo
// Stich.
//Portions created by Frederik Dietz and Timo Stich are Copyright (C) 2003.
//
//All Rights Reserved.
package org.columba.mail.gui.composer.command;

import java.io.IOException;
import java.io.InputStream;

import org.columba.api.command.ICommandReference;
import org.columba.api.command.IWorkerStatusController;
import org.columba.api.gui.frame.IFrameMediator;
import org.columba.core.command.CommandCancelledException;
import org.columba.core.io.StreamUtils;
import org.columba.core.xml.XmlElement;
import org.columba.mail.command.MailFolderCommandReference;
import org.columba.mail.config.MailConfig;
import org.columba.mail.folder.IMailbox;
import org.columba.mail.gui.composer.ComposerModel;
import org.columba.mail.gui.config.template.ChooseTemplateDialog;
import org.columba.mail.gui.tree.FolderTreeModel;
import org.columba.mail.message.IHeaderList;
import org.columba.ristretto.message.MimePart;
import org.columba.ristretto.message.MimeTree;

/**
 * Opens a dialog to ask the user which template to use
 * 
 * @author fdietz
 */
public class ReplyWithTemplateCommand extends ReplyCommand {

	private IFrameMediator mediator;

	public ReplyWithTemplateCommand(IFrameMediator mediator,
			ICommandReference reference) {
		super(reference);

		this.mediator = mediator;
	}

	public void execute(IWorkerStatusController worker) throws Exception {
		// create composer model
		model = new ComposerModel();

		// get selected folder
		IMailbox folder = (IMailbox) ((MailFolderCommandReference) getReference())
				.getSourceFolder();

		// get first selected message
		Object[] uids = ((MailFolderCommandReference) getReference()).getUids();

		// ->set source reference in composermodel
		// when replying this is the original sender's message
		// you selected and replied to
		MailFolderCommandReference ref = new MailFolderCommandReference(folder,
				uids);
		model.setSourceReference(ref);

		// setup to, references and account
		initHeader(folder, uids);

		// get mimeparts
		MimeTree mimePartTree = folder.getMimePartTree(uids[0]);

		XmlElement html = MailConfig.getInstance().getMainFrameOptionsConfig()
				.getRoot().getElement("/options/html");

		// Which Bodypart shall be shown? (html/plain)
		MimePart bodyPart = null;

		if (Boolean.valueOf(html.getAttribute("prefer")).booleanValue()) {
			bodyPart = mimePartTree.getFirstTextPart("html");
		} else {
			bodyPart = mimePartTree.getFirstTextPart("plain");
		}

		if (bodyPart != null) {
			// setup charset and html
			initMimeHeader(bodyPart);

			Integer[] address = bodyPart.getAddress();

			String quotedBodyText = createQuotedBody(bodyPart.getHeader(),
					folder, uids, address);

			// get answer from template
			String templateBody = getTemplateBody();

			model.setBodyText(quotedBodyText + templateBody);
		} else {
			model.setBodyText(getTemplateBody());
		}
	}

	private String getTemplateBody() throws Exception,
			CommandCancelledException, IOException {
		// template folder has uid=107
		IMailbox templateFolder = (IMailbox) FolderTreeModel
				.getInstance().getFolder("107");

		// retrieve headerlist of tempate folder
		IHeaderList list = templateFolder.getHeaderList();

		// choose template
		ChooseTemplateDialog d = new ChooseTemplateDialog(mediator.getView()
				.getFrame(), list);

		Object uid = null;

		if (d.isResult()) {
			// user pressed OK
			uid = d.getUid();
		} else {
			throw new CommandCancelledException();
		}

		// get bodytext of template message
		MimeTree tree = templateFolder.getMimePartTree(uid);

		// *20030926, karlpeder* Added html support
		// MimePart mp = tree.getFirstTextPart("plain");
		MimePart mp;

		if (model.isHtml()) {
			mp = tree.getFirstTextPart("html");
		} else {
			mp = tree.getFirstTextPart("text");
		}

		InputStream bodyStream = templateFolder.getMimePartBodyStream(uid, mp
				.getAddress());

		String body = StreamUtils.readCharacterStream(bodyStream).toString();

		bodyStream.close();
		return body;
	}
}